package com.vinjune.zookeeper.base;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * Created by 000376 on 2017/11/18.
 */
public class ConnectionWatcher implements Watcher {

    private static final int SESSION_TIMEOUT = 5000;

    private static final String HOST = "127.0.0.1:2181";

    protected ZooKeeper zk;

    CountDownLatch connectedSignal = new CountDownLatch(1);

    public void connect() throws IOException, InterruptedException {
        zk = new ZooKeeper(HOST, SESSION_TIMEOUT, this);

        connectedSignal.await();
    }

//    @Override
    public void process(WatchedEvent event) {
        if (event.getState() == Watcher.Event.KeeperState.SyncConnected) {
            connectedSignal.countDown();
            System.out.print("has connected!");
        }
    }

    public void close() throws InterruptedException {
        zk.close();
    }
}
